﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebNext.UI.Models.Contact;
using WebNext.UI.Utils;
using WebNext.UI.Properties;
using WebNext.UI.Utils.Mailing;
using System.Text;

namespace WebNext.UI.Controllers
{
	public class ContactController : BaseController
	{
		public ActionResult SendMessage()
		{
			ContactViewModel contantModel = this.TempData[Constants.Temp] as ContactViewModel;
			if (contantModel == null)
			{
				contantModel = new ContactViewModel(this.IsLogged);
			}

			return this.View(contantModel);
		}

		[HttpPost]
		[ValidateInput(false)]
		public ActionResult SendMessage(ContactViewModel contactModel)
		{
			ValidationResult validationResult = contactModel.Validate();
			if (validationResult.IsValid)
			{
				this.SendMessage(contactModel);
				this.TempData[Constants.Message] = Resources.MessageSent;
			}
			else
			{
				this.TempData[Constants.Message] = validationResult.GetErrorsMessage();
				this.TempData[Constants.Temp] = contactModel;
			}
			return this.RedirectToAction("SendMessage");
		}

		[HttpPost]
		[ValidateInput(false)]
		public ActionResult SendMessageAjax(ContactViewModel contactModel)
		{
			bool result = false;
			List<string> messages = new List<string>();
			
			CaptchaConfiguration captchConfig = CaptchaHelper.CreateCaptcha(this.HttpContext);
			int captchaValueA = captchConfig.A;
			int captchaValueB = captchConfig.B;
			string captchaKey = captchConfig.CaptchaKey;

			ValidationResult validationResult = contactModel.Validate();
			if (validationResult.IsValid)
			{
				this.SendEmail(contactModel);
				messages.Add(Resources.MessageSent);
				result = true;
			}
			else
			{
				messages.AddRange(validationResult.GetErrors());
				result = false;
			}

			return new JsonResult
			{
				Data = new
				{
					messages = messages.ToArray(),
					result = result,
					captchaValueA = captchaValueA,
					captchaValueB = captchaValueB,
					captchaKey = captchaKey,
					isSenderValid = contactModel.IsSenderValid,
					isMessageContentValid = contactModel.IsMessageContentValid,
					isCaptchaValid = contactModel.IsCaptchaValid,
				}
			};
		}

		private void SendEmail(ContactViewModel contactModel)
		{
			string subject = string.Format("WebNext contact: message from {0}", contactModel.Sender);
			
			StringBuilder bodyBuilder = new StringBuilder();
			bodyBuilder.AppendFormat("Sender: {0}\n", contactModel.Sender);
			bodyBuilder.AppendFormat("Email: {0}\n", contactModel.Email);
			bodyBuilder.AppendLine();
			bodyBuilder.AppendLine("Message:");
			bodyBuilder.Append(contactModel.MessageContent);

			IEmailNotifier emailNotifier = new GmailNotifier();
			emailNotifier.Notify(subject, bodyBuilder.ToString());
		}
	}
}
